package com.yenroc.invoice.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author heyanpeng
 * @date 2024年06月28日 16:40
 */
@Slf4j
public class SerializationCloner {

    public static <T extends Serializable> T deepCopy(T original) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            // 序列化
            oos = new ObjectOutputStream(bos);
            oos.writeObject(original);
            oos.flush();

            // 反序列化
            ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bin);
            return (T) ois.readObject();

        } catch (Exception e) {
            log.error("SerializationCloner#deepCopy exception ", e);
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    log.error("SerializationCloner#deepCopy oos close error ", e);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    log.error("SerializationCloner#deepCopy ois close error ", e);
                }
            }
        }
        return null;
    }

}
